from pylons import g
import pyleo.lib.helpers as h
import time, os 
class BlogCalendar:

    def __init__(self,path):
        """
        this is called by the menu but we get the context from the
        request itself.
        """
        #path=request.environ['PATH_INFO']

        # five cases:
        #    blog:  - serve up latest month 
        #    blog/year - serve up Jan
        #    blog/year/month - serve up year/month
        #    blog/year/month/day - serve up year/month
        #    anything else - serve up latest month
        # where of course blog is the config blog prefix ...

        self.blog_path=g.blog_path
        self.lfs_root=g.lfsroot
        self.home_href=g.home_href
        path=path.strip('/')
        if path.startswith(self.blog_path):
            parts=path.strip(self.blog_path).split('/')[1:]
            #assume we have blog_path/year/month/day
            try:
                y=int(parts[0])
                if len(parts)==1:
                    m=1
                else:
                    m=int(parts[1])
            except:
                y,m=time.gmtime()[0:2]
        else: 
            # serve up latest month
            y, m = time.gmtime()[0:2]

        year, last, this, next = self.title_links(y, m)

        self.html = HtmlCalendar(y, m, self.day_links(y, m), (last, next), this, year)
        
    def get_html(self):
        return self.html
                 
    def day_links(self,y,m):

        # Jump directly down to the month ...
        links = {}
        base = "".join([self.blog_path, "/", str(y), "/", "%2.2i" % m])
        monthdir = self.lfs_root + base
        if os.path.isdir(monthdir):
            blogs = os.listdir(monthdir)
            for blog in blogs:
                if blog[0:1] != ".":
                    links[int(blog)] = base + "/" + blog
        return links

            
    def title_links(self,y,m):

        def yeartitle(y):
            return "/".join([g.site_url,self.blog_path, str(y)])

        def increment(y, m, i):
            mm = m + i
            yy = y
            if mm > 12:
                mm, yy = mm % 12, y + mm / 12
            elif mm < 1:
                mm, yy = 12 + mm, y - 1
            return yy, mm
            
        plus = increment(y, m, 1)
        minus = increment(y, m, -1)
        year = yeartitle(y)
        print 'bnl', year
        this = "%s%s%2.2i" % (year, "/", m)
        next = "%s%s%2.2i" % (yeartitle(plus[0]), "/", plus[1])
        last = "%s%s%2.2i" % (yeartitle(minus[0]), "/", minus[1])
        return year, last, this, next             

month_names = ["January ", "February ", "March ", "April ", "May ", "June ",
               "July ", "August ", "September ", "October ", "November ", "December "]
 
def HtmlCalendar(year, month, links={}, arrows=None, monthlink=None, yearlink=None):
    """
    Produces an html table representation of the month. If the links
    argument is passed then it should consist of a set of links keyed by day
    of the month. If the arrows argument is passed, then it should consist of
    a two member tuple which has the links to the previous and next month.
    If the monthlink argument is passed, then it should be used as a link
    from the month title, if the yearlink argument is passed it can be used as
    the yearlink title.
    """
   
    months = ["January ", "February ", "March ", "April ", "May ", "June ",
              "July ", "August ", "September ", "October ", "November ", "December "]

    # Ok, I know I should be able to find someone elses code to do this,
    # but it'll take longer to find it than write it
    
    import calendar

    def makelink(target, link):
        return "".join(['<a href="',target,'">',link,"</a>"])

    def monthtitle(m, link, short=0):
        title = months[m - 1]
        if short:
            title = title[0:3]
        if link is None:
            return title
        else:
            return makelink(link, title)

    tr=("<tr>","</tr>")
    td=("""<td align="center">""","</td>")
   
    if yearlink == None:
        yeartitle = str(year)
    else:
        yeartitle = makelink(yearlink, str(year))

    if arrows == None:
        template = "".join(["""<table><tr><td align="center" colspan="7">""",
                          monthtitle(month, monthlink), yeartitle, "</td></tr>"])
    else:
        template = "".join(["<table><tr>", td[0], makelink(arrows[0], "&lt;&lt;"), 
                          td[1], """<td align="center" colspan="5">""",
                          monthtitle(month, monthlink, short=1), " ",
                          yeartitle, "</td>", td[0],
                          makelink(arrows[1], "&gt;&gt;"), td[1], tr[1]])
    
    template += tr[0]
    for day in ("Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"):
        template += "".join([td[0], day, td[1]])

    template += tr[1]
    matrix = calendar.monthcalendar(year, month)
    for week in matrix:
        row = tr[0]
        for day in week:
            if day != 0:
                if day not in links.keys():
                    row += "".join([td[0], str(day), td[1]])
                else:
                    row += "".join([td[0], makelink(links[day], str(day)), td[1]])
            else:
                row += "".join(td)
        row += tr[1]
        template += row
    template += "</table>"
    
    return template
